GithubHelp home page GithubHelp logo

webpack-contrib / raw-loader Goto Github PK

View Code? Open in Web Editor NEW
846.0 17.0 89.0 1.48 MB

A loader for webpack that allows importing files as a String

License: MIT License

JavaScript 100.00%
webpack-loader raw files

raw-loader's Introduction

npm node deps tests coverage chat size

raw-loader

DEPREACTED for v5: please consider migrating to asset modules.

A loader for webpack that allows importing files as a String.

Getting Started

To begin, you'll need to install raw-loader:

$ npm install raw-loader --save-dev

Then add the loader to your webpack config. For example:

file.js

import txt from './file.txt';

webpack.config.js

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/i,
        use: 'raw-loader',
      },
    ],
  },
};

And run webpack via your preferred method.

Options

Name Type Default Description
esModule {Boolean} true Uses ES modules syntax

esModule

Type: Boolean Default: true

By default, raw-loader generates JS modules that use the ES modules syntax. There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.

You can enable a CommonJS module syntax using:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/i,
        use: [
          {
            loader: 'raw-loader',
            options: {
              esModule: false,
            },
          },
        ],
      },
    ],
  },
};

Examples

Inline

import txt from 'raw-loader!./file.txt';

Beware, if you already define loader(s) for extension(s) in webpack.config.js you should use:

import css from '!!raw-loader!./file.txt'; // Adding `!!` to a request will disable all loaders specified in the configuration

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

raw-loader's People

Contributors

alexander-akait avatar cap-bernardito avatar evilebottnawi avatar frankfang avatar fresheneesz avatar joeheyming avatar joshwiens avatar kevinzwhuang avatar michael-ciniawsky avatar montogeek avatar niksy avatar nocke avatar rdil avatar shama avatar shellscape avatar simon04 avatar sokra avatar spacek33z avatar thelarkinn avatar tillsanders avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

raw-loader's Issues

raw-loader 2.0 not working with pug-html-loader

  • Operating System: macOS 10.14.3
  • Node Version: 10.15.2
  • NPM Version: 6.9.0
  • webpack Version: 4.29.6
  • raw-loader Version: 2.0.0
  • pug-html-loader Version: 1.1.5

Expected Behavior

This part of my webpack config (module.rules) will work with raw-loader 2.0.0 the same way it worked with raw-loader 1.0.0:

        {
          test: /\.pug$/,
          use: ['raw-loader', 'pug-html-loader']
        }

Actual Behavior

Pug templates were not loaded.

Code

        {
          test: /\.pug$/,
          use: ['raw-loader', 'pug-html-loader']
        }
  // additional code, HEY YO remove this block if you don't need it

How Do We Reproduce?

Use the pug-html-loader 1.1.5 with a small website that uses pug templates (such as a default site built using generator-angular-fullstack (yeoman).

Link to my webpack config

Sourcemap support.

In Angular2 Components, you have the ability to pass a stringified css style to a decorator like below:

import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'test-eight-app',
  templateUrl: 'test-eight.component.html',
  styles: [require('./styles.scss')]
})
export class TestEightAppComponent {
  foo: string = "someInformation";
  title = 'test-eight works!';
  anArray: number[] = [1,2,3,4,5,6,7,8,9,10];
}

The common usecase with webpack is to require it and use raw loader to inline the file (or chain it though raw-loader and another loader, however raw-loader doesn't have sourcemap support built it.

Could we implement sourcemap support into the loader so that preprocessed files that are require()d are available. The webpack config usecase looks like this:

      {
        test:/\.styl$/,
        loaders: ['raw-loader', 'stylus-loader?sourceMap']
      },
      {
        test:/\.less$/,
        loaders: ['raw-loader', 'less-loader?sourceMap']
      },
      {
        test:/\.scss$/,
        loaders: ['raw-loader', 'sass-loader?sourceMap']
      },

version 2.0.0 breaks ng Angular 8 -> webpack in my project

  • Operating System: Ubuntu 19.04
  • Node Version: 12.2.0
  • NPM Version: - I use yarn for most, but npm 6.9.0
  • webpack Version: 4.33.0
  • raw-loader Version: 2.0.0
        Angular CLI: 8.0.1
        Node: 12.2.0
        OS: linux x64
        Angular: 8.0.0
        ... common, compiler, compiler-cli, core, elements, forms
        ... platform-browser, platform-browser-dynamic, router
        
        Package                           Version
        -----------------------------------------------------------
        @angular-devkit/architect         0.800.1
        @angular-devkit/build-angular     0.800.1
        @angular-devkit/build-optimizer   0.800.1
        @angular-devkit/core              8.0.1
        @angular-devkit/schematics        8.0.1
        @angular/cli                      8.0.1
        @angular/http                     7.2.15
        @schematics/angular               8.0.1
        @schematics/update                0.800.1
        rxjs                              6.5.2
        typescript                        3.4.5
        webpack                           4.33.0

Expected Behavior

not to see my web app crash:

VM568 vendor.js:14467 Uncaught Error: Expected 'styles' to be an array of strings.
    at assertArrayOfStrings (VM568 vendor.js:14467)
    at 
assertArrayOfStrings (vendor.js:14467)
push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNonNormalizedDirectiveMetadata (vendor.js:29784)
push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getEntryComponentMetadata (vendor.js:30429)
(anonymous) (vendor.js:30420)
push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getEntryComponentsFromProvider (vendor.js:30419)
(anonymous) (vendor.js:30392)
push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getProvidersMetadata (vendor.js:30355)
(anonymous) (vendor.js:30357)
push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getProvidersMetadata (vendor.js:30355)
(anonymous) (vendor.js:29978)
push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (vendor.js:29969)
push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._loadModules (vendor.js:36121)
push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (vendor.js:36102)
push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler.compileModuleAsync (vendor.js:36062)
push../node_modules/@angular/platform-browser-dynamic/fesm5/platform-browser-dynamic.js.CompilerImpl.compileModuleAsync (vendor.js:73377)
compileNgModuleFactory__PRE_R3__ (vendor.js:62274)
push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule (vendor.js:62483)
./src/main.ts (main.js:23343)
__webpack_require__ (runtime.js:79)
0 (main.js:29591)
__webpack_require__ (runtime.js:79)
checkDeferredModules (runtime.js:46)
webpackJsonpCallback (runtime.js:33)
(anonymous) (main.js:1)

Actual Behavior

no errors on web side.

Code

This code that crashes is the straight Angular 8.0, and I suspect Angular 7.0 as well. I saw this earlier and back off from v2.0.0 to v1.0.0 on raw-loader.
So the question is, what could the raw loader do that could be calling without the strings and just a [Module]?

How Do We Reproduce?

Not sure, without my source and project.

Are there log messages that can be turned on in the raw-loader the could spit out what is IN and OUT. Then I could run it under v1.0.0 and then under v 2.0.0. I suspect that seeing the log, would probably determine the difference between 2.0.0 and 1.0.0.
I would be happy to do that and report back. Thanks!

Looking into the failure point in chrome, it fails at : assertArrayOfStrings(), which is being called with args:

identifier = "styles", value = [Module]

        function assertArrayOfStrings(identifier, value) {
            if (value == null) {
                return;
            }
            if (!Array.isArray(value)) {
                throw new Error("Expected '" + identifier + "' to be an array of strings.");
            }
            for (var i = 0; i < value.length; i += 1) {
                if (typeof value[i] !== 'string') {
                    throw new Error("Expected '" + identifier + "' to be an array of strings.");
                }
            }
        }
        

The webpack, is straight from ng - Angular 8. I could not attach angular.json on GitHub as a json file, so here it is as a txt file:
angular.txt

Raw loader adds an extra module.exports = in the bundle.

Using webpack 2.2.1 & raw-loader 0.5.1

The raw-loader will append extra module.exports into the template that is included into the bundle.

Here's an example bundled snippet:

/***/ "../node_modules/raw-loader/index.js!./components/template.html":
/***/ (function(module, exports) {

module.exports = "module.exports = \"<div>\\r\\n    I'm a template\\r\\n    </div>\""

/***/ }),

.template.html :

<div>
    I'm a template
</div>

Note the extra module.exports = in the template text

New version doesn't work properly

New version doesn't work properly with Webpack and Angular

"compiler.es5.js:1694 Uncaught Error: The template specified for component AppComponent is not a string"...

Webpack: 3.6.0
Angular: 4.4.4

But in your previous version "0.5.1" all works fine

Provide option to return null instead of an error if file cannot be found

When requiring a file dynamically, it it cannot be found I get:

Uncaught Error: Cannot find module './www/assets/scss/components/_Form.scss'.
    at www.*$:29
    at webpackContextResolve (www.*$:29)
    at webpackContext (www.*$:26)
    at AppPanelScss (appPanelScss.jsx:17)
    at ReactCompositeComponent.js:306
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._constructComponentWithoutOwner (ReactCompositeComponent.js:305)
    at ReactCompositeComponentWrapper._constructComponent (ReactCompositeComponent.js:280)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:188)
    at Object.mountComponent (ReactReconciler.js:46)

I would like to either provide an option to return a null value or set up a config that it just returns an empty string or null.

Module Not Found

  • Operating System: 10.14.6
  • Node Version: v10.20.1
  • NPM Version: 6.14.4
  • webpack Version: 4.4
  • raw-loader Version: 4.0.1

Expected Behavior

Adding raw loader to import markdown files:

  test: /\.md$/i,
      use: [{
        loader: 'raw-loader',
        options: {
          esModule: false
        }
      }],

In .js file, require the markdown file..

return require(postPath)
// postPath is '../posts/awards.md'
Error: Cannot find module '../posts/awards.md'
at webpackEmptyContext (eval at <path to file>)
....

the path to markdown file is the relative path: /posts/awards.md

The variable contains the path to the file instead of the text

The cities variable contains the path to the file instead of the text:

module.exports = __webpack_public_path__ + "static/media/cities.b4c5b41d.txt";

My code:

import cities from './cities.txt';

Config:

    rules: [
		{
			test: /\.txt$/,
			use: 'raw-loader'
		}
    //....
     ]

`Module not found` when using TypeScript project references

  • Operating System: OSX Catalina
  • Node Version: 12.10.0
  • NPM Version: 6.14.5
  • webpack Version: 4.43.0
  • raw-loader Version: 4.0.1

Expected Behavior

When using raw-loader with TypeScript references— For any given module X.ts, I'd expect import paths relative to X.ts to refer to the same resources whether X is imported from within its own project, or from a module in a different project.

Clone https://github.com/trbabb/rawloader-repro.git, and after npm install, run npx webpack. I'd expect src/Foo.ts to find ./shad/foo.frg and import it normally.

Actual Behavior

npx webpack in the above repo yields:

ERROR in /project/path/src/Foo.ts
./src/Foo.ts
[tsl] ERROR in /project/path/src/Foo.ts(1,19)
      TS2307: Cannot find module './shad/foo.frg' or its corresponding type declarations.

This is not the case if src/Foo.ts is compiled from within its own project. This can be seen if you:

> mv webpack.config.js webpack.config.js-broken
> mv webpack.config.js-working webpack.config.js
> npx webpack

This compiles normally, and the contents of foo.frg can be found inside the bundle as expected.

Somehow, the existence of project reference breaks the relative path in src/Foo.ts.

Code / How to reproduce

git clone https://github.com/trbabb/rawloader-repro.git
npm install
npx run webpack

Please let me know if there's anything I need to configure differently to get this to work. Thanks!

webpack-defaults upgrade

Addition of webpack-defaults & associated refactoring as a part of the next Major release

Issue exists for status tracking across the organization.

Please do not close

raw-loader does not working with Jasmine test for Angular 5

When I attempt to write a simple integration test for Angular 5 I get the following error when trying to configure my TestBed:
Error: Cannot find module 'raw-loader!./demo-text.md' from 'MyComponent'

Has anyone else experienced this testing Angular 5 applications which make use of raw-loader? Thanks for your time.

Cannot require a txt file

I am trying to import a .txt file using raw-loader.
If I use var text=require(raw!./sample.txt) I get raw!./sample.txt not fount and if I use var txt=require(./sample.txt) I get this error:

(function (exports, require, module, __filename, __dirname) { html ....} SyntaxError: Unexpected token { at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10) at Module._compile (module.js:542:28) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object.<anonymous>

Can anyone explain?

When i use style-loader after raw-loader i get error

My webpack rule is as follows:

  {
    "exclude": [],
    "test": /\.css$/,
    "use": [
      {
        "loader": "style-loader"
      },
      {
        "loader": "raw-loader"
      },
      {
        "loader": "postcss-loader",
        "options": {
          "ident": "embedded",
          "plugins": postcssPlugins,
          "sourceMap": true
        }
      }
    ]
  }

but i get this error in the browser:

  Uncaught Error: Expected 'styles' to be an array of strings.
at assertArrayOfStrings (compiler.js:2522)
at CompileMetadataResolver.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:14965)
at CompileMetadataResolver.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.CompileMetadataResolver._getEntryComponentMetadata (compiler.js:15854)
at compiler.js:15835
at Array.forEach (<anonymous>)
at CompileMetadataResolver.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.CompileMetadataResolver._getEntryComponentsFromProvider (compiler.js:15834)
at compiler.js:15789
at Array.forEach (<anonymous>)
at CompileMetadataResolver.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.CompileMetadataResolver._getProvidersMetadata (compiler.js:15752)
at compiler.js:15754

I think raw loader doesn't return correct output.

SyntaxError: Unexpected token

This is my test component (works well without trying raw-loader):

import test from "raw-loader!./test.txt";

class Application extends React.Component {
    componentWillMount() {
        console.log(test);
    }
}

This is test.txt content:
some text here

This is what I'm getting when trying to build by webpack:

ERROR in ./~/raw-loader!./src/app/test.txt
Module build failed: SyntaxError: Unexpected token, expected ; (1:5)

> 1 | some text here
    |      ^

 @ ./src/app/Application.jsx 13:12-44

Using "raw-loader": "^0.5.1".
Tried with both Webpack v1 (1.14.0) and v2 (2.2.1), result is the same.
What am I doing wrong?!

Watch not working

Hi everyone,

It seems that the files imported with raw-loader are not watched by webpack. :(

My config :

{
    ...,
    module: {
        rules: [
            ...,
            {
                loader: 'raw-loader',
                test: /\.md$/i
            }
        ]
    }
}

My config is :

  • webpack : 4.43.0
  • raw-load : 4.0.1
  • node : 12.11.1
  • running on Mac 10.14.5

Is anyone has encountered this issue ?

I found a similar issue here : https://stackoverflow.com/questions/45515724/webpack-watch-doesnt-trigger-for-css-files-in-specific-directory but the suggested solution is not very effective (re-run the whole webpack process instead of just the needed file).

Thanks.

Weird behaviour of loader on Docker

Hi
I am using raw-loader to load raw xml files in my react project with the following config in my rules for loader.

   { 
        test: /\.xml$/,
        exclude: /node_modules|src/,
        loader: 'raw-loader'
      }

And build my output with webpack --config webpack.build.config. The weird problem is that on my local machine or any machine loader works correctly and emits out xml files as string in the compiled JS.
However, when running inside the docker environment it always complain,

ERROR in ../test/gizmos/FractionPie.xml
Module parse failed: /src/test/gizmos/FractionPie.xml Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <semantics>
|   <mrow>
|     <mn>2590</mn>

I also tried putting console log in the module code itself to check if it is being registered loader and being invoked or not. On local machine, I see all console logs along with content. On Docker it is not even being recognized as the loader and none of the console.log messages appear.

Removing line breaks

https://www.google.ru/search?newwindow=1&q=browser+renders+line+breaks&spell=1&sa=X&ved=0ahUKEwiCw4mVtfrWAhUnYZoKHRsEDvEQvwUIIygA&biw=1201&bih=867

Hello people.
What do you think about adding a "\n" strip option into raw-loader.
While remaking my templates from['<span></span>', '<span></span>'].join('')stuff to modern require ('tpl.html') I SUDDENLY came across the issue with markup, it actually changed, because raw-loader puts line breaks into output. Inline elements became rendered incorrectly. Using float is an ugly crappy stuff as I see it.

I will definitely fork that and add newline stripping, but do you think it is worth a pull request?

Imported string contains module.exports

  • Operating System: Windows
  • Node Version: 8.9.1
  • NPM Version: 6.7.0
  • webpack Version: 4.29.0
  • raw-loader Version: 1.0.0

Expected Behavior

Raw document contents are imported as string.

Actual Behavior

Imported string is

'module.exports = "file contents"'

Code

  // webpack.config.js
  ...
  module: {
    rules: [
      {
        test: /\.txt$/,
        use: 'raw-loader'
      }
    ]
  }
  ...

Also tried 'raw-loader!file-name.md'.

How Do We Reproduce?

I'm using Nuxt (might be relevant somehow). I just want to load an md file to a string and then render it.

Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = "{\...'

  • Operating System:
    macOS Mojave: 10.14
  • Node Version:
    v10.15.1
  • NPM Version:
    6.4.1
  • webpack Version:
    4.29.3
  • raw-loader Version:
    1.0.0

Expected Behavior

To load load this json file:

{
  "expo": {
    "name": "My Awesome Project",
    "slug": "my-awesome-project",
    "privacy": "public",
    "sdkVersion": "32.0.0",
    "platforms": [
      "ios",
      "android"
    ],
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/icon.png",
    "splash": {
      "image": "./assets/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "ios": {
      "supportsTablet": true
    }
  }
}

Actual Behavior

Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = "{\...'
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token m in JSON at position 0 while parsing near 'module.exports = "{\...'
    at JSON.parse (<anonymous>)

Code

<div style={{fontSize: 28}}>
<CodeSurfer
  title="Development Path - Splash Screen"
  code={require('!raw-loader!../my-awesome-project/app.json')}
  showNumbers={false}
  dark={true}
  lang="json"
  steps={[
    { range: [15, 15], notes: 'To setup a splash screen, just add a file named splash.png to assets folder'},
  ]}
/>

How Do We Reproduce?

check this repo: https://github.com/jgcmarins/react-native-cryptocurrency

`import * as files from '!raw-loader!./foo';` issue

I’m not sure if this is the best place for this question, so I'm happy to remove the issue if so.

With normal JS files I can import them like this:import * as foo from ‘../some/dir'; and then call it later foo[‘bar’]. I’d like to be able to do the same thing, but with the inline raw loader. Something like: import * as files from ‘!raw-loader!../some/dir’; and then call the raw file later: files[‘some-file]. But that doesn’t work. It parses the raw file into a JSON object with each letter as a key.
Is there a good way to do that?

Not working with require statements

  • Operating System:
    macOS Mojave

  • Node Version:
    8.9.1

  • NPM Version:
    6.5.0

  • webpack Version:
    4.29.6

  • raw-loader Version:
    2.0.0

Expected Behavior

import and require should both inline the file contents

Actual Behavior

importworks, but require doesn't.

Code

example:

import Test from '../../../shader/pbr.glslv'
const Test2 = require('../../../shader/pbr.glslv')

when logging both in the console, for Test I get the contents of the file, but for Test2 I get

Module {default: "//camera.matrixWorld
↵uniform mat4 viewMatrixInver…tion = projectionMatrix * positionInViewSpace;
↵}", __esModule: true, Symbol(Symbol.toStringTag): "Module"}

I used to run webpack 3.8.1 and raw-loader 0.5.1 before and there everything worked. It stopped working after upgrading everything to the latest version.

module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            plugins: [
              "transform-decorators-legacy",
              "react-hot-loader/babel"
            ],
            presets: [
              "env", "react", "stage-1"
            ]
          }
        }
      },
      {
        test: /\.(glslf|glslv)$/,
        use: 'raw-loader'
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ["style-loader", "postcss-loader"]
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack-loader'
        ]
      }
    ]
  },

How Do We Reproduce?

Use import and require on the same file and console.log the result

[Bug Report] raw-loader failed to load *.json

  • Operating System: OSX
  • Node Version: v12.16.1
  • NPM Version: 6.13.4
  • webpack Version: 4.42.1
  • raw-loader Version: 4.0.1

Expected Behavior

*.json should be loaded successfully with raw-loader like the *.js;

Actual Behavior

*.json cannot be loaded successfully.

Code

import foo from 'raw-loader!./foo.json' // don't work
// import foo from 'raw-loader!./foo.js' // work

export default {
  foo,
}

How Do We Reproduce?

I just created a minimal reproduction repo: raw-loader-load-json-repro, and here're the reproduction steps:

  1. git clone https://github.com/ulivz/raw-loader-load-json-repro
  2. yarn
  3. npx webpack
  4. You'll got following error:

  1. Modify entry index.js,comment json import and uncomment js import:
- import foo from 'raw-loader!./foo.json' // don't work
+ // import foo from 'raw-loader!./foo.json' // don't work
- // import foo from 'raw-loader!./foo.js' // work
+ import foo from 'raw-loader!./foo.js'

export default {
  foo,
}

Ru-run npx webpack,the build will be success.

Requiring raw jsx file still precompiles it

I'm requiring raw jsx file: require('raw!./Test.jsx')

In webpack config I have jsx-loader:

//...
module: {
    loaders: [
        {test: /\.jsx$/, loader: 'jsx?harmony'},
    ]
}
// ...

In Test.jsx:

class Test {}

What I get (precompiled JS):

()(function() { var siteObj = ["\nclass Test {}\n"]; siteObj.raw = ["\nclass Test {}\n"]; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()

)(function() { var siteObj = [""]; siteObj.raw = [""]; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }())

What I expect (raw js):

class Test {}

raw-loader throws an error while parsing mustache templates

I'm seeing this error:

WARNING in ./src/excisor/templates/book.txt.mustache
Module parse failed: C:\Users\altano\Documents\Projects\MMM\src\excisor\templates\book.txt.mustache Line 4: Unexpected token ILLEGAL

while parsing book.txt.mustache:

{{title}}
{{authors}}

{{#highlights}}{{> highlight}}{{/highlights}}
{{^highlights}}You have no highlights for this book yet.{{/highlights}}

like so:

var Mustache = require("mustache");

require("raw-loader");

var highlightTextTemplateSource = require("raw!!excisor/templates/highlight.txt.mustache");
Mustache.compilePartial("highlight", highlightTextTemplateSource);

var bookTextTemplateSource = require("raw!!excisor/templates/book.txt.mustache");
var bookTextTemplate = Mustache.compile(bookTextTemplateSource);

Funny story though: I don't see anything wrong with the raw-loader AND the loader still appears to return the correct source... I see nothing wrong with the webpack output.

I'll write a mustache-loader modeled after the jade-loader but I thought I'd still mention this.

Cannot import file using typescript

  • Operating System: OSX
  • Node Version: v8.11.3
  • NPM Version: 5.6.0
  • webpack Version: ^4.19.1
  • raw-loader Version: ^0.5.1

This issue is for a:

  • bug
  • feature request
  • modification request

Code

import txt from './simple.txt'
CLI Command
  webpack
webpack.config.js

webpack.config.js

tsconfig
{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5"
  },
  "include": [
    "./src/**/*"
  ]
}

Expected Behavior

Should load the file and return a string to txt

Actual Behavior

Get the following error after running webpack

ERROR in [at-loader] ./src/index.ts:3:17
    TS2307: Cannot find module './simple.txt'.

How Do We Reproduce?

Simply use the webpack config and import. package.json can be provided as well.

Not really sure if this is an error with the loader, webpack, my config, or awesome-typescript-loader

Also before you asked, I also tried import txt from 'raw-loader!./simple.txt' and import txt from './simple.txt', no dice.

Thanks!

Minor mistake in readme.md?

Readme.md says:

import txt from 'file.txt';

Do you mean

import txt from './file.txt';

(the first version would afaik mean, “there's a file.txt module”. The second does work for local .txt files in your entry point's folder)

Can raw-loader catch all

The example in the README.md suggests .txt$ has to be configured in order for this loader to load .txt file. I wonder if this loader could be configured as a catch all loader, meaning it could catches everything not caught by other loaders?

The provided value <path> is not an absolute path!

Hi, I updated the raw-loader version to it latest and started getting this message:

The provided value "./app-www/components/" is not an absolute path!

If I change "./app-www/components/" to the absolute path to the file("/home/user....") it works correctly but that solution is not suitable for team work.

The actual configuration is like this:

module: {
    loaders: [{
        test: /\.html$/,
        loader: "raw-loader",
        include: './app-www/components/',
        query: {
            minimize: true
        }
    }]
},

How can I make this loader work the way it did before? Is this a bug?

Thanks

Does not work with a dynamic path

Whenever I try to use this with a dynamic require path it fails. Is this normal are can this be circumvented somehow?

For example these will fail:

var name = 'arrow.svg';
require('!!raw-loader!public/images/svg/ + name');
var name = 'arrow.svg';
require(`!!raw-loader!public/images/svg/${name}`);

While this works fine:

require('!!raw-loader!public/images/svg/arrow.svg');

The error I get is:

ERROR Failed to compile with 1 errors 2:45:45 PM

This dependency was not found:

  • !!raw-loader!public/images/svg/ in .//babel-loader/lib?{"cacheDirectory":true,"presets":[["env",{"modules":false,"targets":{"browsers":["> 2%"],"uglify":true}}]]}!.//vue-loader/lib/selector.js?type
    =script&index=0!./resources/assets/js/components/svg/SvgInline.vue

To install it, you can run: npm install --save !!raw-loader!public/images/svg/

Warning/Failure Using Raw Loader 2.0.0 in Angular CLI

  • Operating System: Windows 7
  • Node Version: 11.13.0
  • NPM Version: 6.7.0
  • webpack Version: webpack included in Angular 7.2.11/ Angular CLI 7.3.7
  • raw-loader Version: 2.0.0

Expected Behavior

I expect raw-loader uses to properly read the text contents of my files and stream them into the assigned variable.

Actual Behavior

The following warning is given during build...

"export 'toString' (imported as 'iconSvgs') was not found in '!raw-loader!../../../../styles/my-icons/dist/fonts/icons.svg'

This warning initially seems in line with the started info on the inline section of the README.md page (https://github.com/webpack-contrib/raw-loader/blob/master/README.md#inline) . If the warning is ignored and you continue to try to run the code, of course, the variable is not created (in this case, below, iconSvgs) and the later loading code fails (since raw-loader has not worked).

However, if you make any of the changes as suggested on the page, with the update to 2.0.0, the old referencing notation of raw-loader no longer works inside of Angular CLI projects, and the instructions for how to update the reference do NOT work.

IMPORTANT NOTE: Yes, I did try to change the reference from

import * as iconSvgs from '!raw-loader!../../../../styles/my-icons/dist/fonts/icons.svg';

to

import * as iconSvgs from 'raw-loader!../../../../styles/my-icons/dist/fonts/icons.svg';

and

import * as iconSvgs from '!!raw-loader!../../../../styles/my-icons/dist/fonts/icons.svg';

..However, both those changes resulting in the compile failing outright (as opposed to the warning of the original !raw-loader! syntax). For example, changing to the '!!raw-loader!' format gives the following error:

ERROR in src/app/my-container/components/DrawingSupport/icons.ts(7,27): error TS2307: Cannot find module '!!raw-loader!../../../../styles/my-icons/dist/fonts/icons.svg'.

Code

import * as iconSvgs from '!raw-loader!../../../../styles/my-icons/dist/fonts/icons.svg';

How Do We Reproduce?

Upgrade from raw-loader 1.0.0 to 2.0.0 on a project using latest version of angular cli/angular (Angular 7.2.11/ Angular CLI 7.3.7 ). Using raw-loader 2.0.0 with the default configuration for Angular CLI breaks builds when trying to access this plugin as shown above (the plugin is included and configured inside of Angular CLI and not in angular.json directly).

Isomorphic?

Hi,

I’ve written an isomorphic shim for raw-loader. Works in node and such. node-raw. It’s there mainly for the purpose of testing and rapid development.

@webpack would you mind mentioning it in this project?

error when using with SCSS and angular7

  • Operating System: macOS 10.14.4
  • Node Version: v11.14.0
  • NPM Version: 6.9.0
  • webpack Version: 4.30.0
  • raw-loader Version: 2.0.0

Expected Behavior

Wokring like it does with 1.0.0

Actual Behavior

After upgrading raw-loader to 2.0.0 I always receive this error from Angular:

Uncaught Error: Expected 'styles' to be an array of strings.

Using Angular 7.2.14.

Code

This is my configuration for my SCSS and CSS:

      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loaders: ['raw-loader', 'sass-loader']
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ]
      }

This setup works fine with raw-loader 1.0.0.

Export incompatibility with raw-loader and awesome-typescript-loader

  • Operating System: MacOSX
  • Node Version: 8
  • NPM Version: yarn 1.7.0
  • webpack Version: 4.12.0
  • webpack-serve Version: none

This issue is for a:

  • bug
  • feature request
  • modification request

Code

I have some code to import an SVG in Typescript. Here are some relevant snippets:

Importing an SVG in a typescript file:

import addLgSvg from './add-lg.svg';

const icons = {
   'add-lg': addLgSvg,
};
export default icons;

And of course I have defined this silly typescript module declaration to help:

declare module "*.svg" {
  const content: string;
  export default content;
}
webpack.config.js
// module.rules = [ ...
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
            {
                test: /\.(svg)$/,
                use: [
                    {
                        loader: 'raw-loader',
                    },
                ],
            },
// ... ];

Expected Behavior

SVG should be imported and exported as expected.

Actual Behavior

Somehow there is incompatibility between the raw-loader export and the typescript import.

raw-loader compiles my SVG as:

"./icons/add-lg.svg": /*!**************************!*\
  !*** ./icons/add-lg.svg ***!
  \**************************/
    /*! no static exports found */
    /***/
    (function(module, exports) {

        module.exports = "<svg > ... </svg>\n"

        /***/
    }
    ),

awesome-typescript-loader generates this output however:

    (function(module, exports, __webpack_require__) {

        "use strict";

        Object.defineProperty(exports, "__esModule", {
            value: true
        });

        var add_lg_svg_1 = __webpack_require__(/*! ./add-lg.svg */
            "./icons/add-lg.svg");
        var icons = {
            'add-lg': add_lg_svg_1.default,
        };
        exports.default = icons;
});

In the above snippet, var add_lg_svg_1 is a string with the SVG content. However, it has been compiled to add_lg_svg_1.defeault, which does not exist.

Screenshots:
screen shot 2018-06-19 at 4 59 56 pm

screen shot 2018-06-19 at 5 00 06 pm

How Do We Reproduce?

I can try to produce a limited test case if necessary.

I'm not sure how to resolve this, and whether the culprit is this project or the typescript-loader, or my usage.

doesn't work with webpack2 and angular 1

      template: require('./navbar.html'),


      // raw html
      {
        test: /\.html$/,
        loader: 'raw-loader'
      }



      Uncaught ReferenceError: angular is not defined


      Uncaught Error: [$injector:modulerr] Failed to instantiate module myapp due to:
Error: [$injector:nomod] Module 'myapp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

If I just do templateUrl: './navbar/navbar.html' it works fine.

Angular and Styles

  • Operating System: Windows 10
  • Node Version: 10.15.1
  • NPM Version: 6.7.0
  • webpack Version: see below
  • raw-loader Version: see below

Expected Behavior

webpack is successful

Actual Behavior

webpack is not successful

Code

webpack and raw-loader version are in repo

https://github.com/cheng93/raw-loader-issue

ERROR in Expected 'styles' to be an array of strings.

10 silly lifecycle [email protected]~build: Args: [ '/d /s /c', 'webpack --mode=development' ]
11 silly lifecycle [email protected]~build: Returned: code: 2  signal: null
12 info lifecycle [email protected]~build: Failed to exec build script
13 verbose stack Error: [email protected] build: `webpack --mode=development`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter.<anonymous> (C:\Users\dev\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:189:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Users\dev\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:189:13)
13 verbose stack     at maybeClose (internal/child_process.js:970:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid [email protected]
15 verbose cwd C:\code\cheng93\raw-loader-issue
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\dev\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
18 verbose node v10.15.1
19 verbose npm  v6.7.0
20 error code ELIFECYCLE
21 error errno 2
22 error [email protected] build: `webpack --mode=development`
22 error Exit status 2
23 error Failed at the [email protected] build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

Question: How to import raw files with resolved imports

Hi, I would like to import a file as a string but only after webpack has resolved the importstatements inside of it.

Is that possible?

Basically:

// file bar
export const foo = 'I am a string'
// File 1
import {foo} from './bar'
// more stuff
import fileAsString from 'raw-loader!./file1'
// resolved {foo} + more stuff

Kind/Question Is this the normal behaviour?

Code

let text = require("./text.txt");
let svg = require("./ic_list_black_48px.svg");
console.log(text);
console.log(svg);

test.txt & ic_list_black_48px.svg are completly the same

<svg fill="#000000" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg">
    <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/>
    <path d="M0 0h24v24H0z" fill="none"/>
</svg>

Console

playlist.tsx?1942:15
<svg fill="#000000" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg">
    <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/>
    <path d="M0 0h24v24H0z" fill="none"/>
</svg>

playlist.tsx?1942:16
module.exports = "data:image/svg+xml;base64,bW9kdWxlLmV4cG9ydHMgPSAiZGF0YTppbWFnZS9zdmcreG1sO…

Different behavior when using webpack2

I am using the raw-loader to inline some SVG / HTML as raw strings. With webpack it worked fine. With webpack2 I am getting:

<button>
module.exports = __webpack_public_path__ + "src/lib/icons/button.svg";
</button>

while with webpack1:

<button>
<svg>
    ...
</svg>
</button>

with html-loader, the html-loader parse fail

where used with html-loader, the html complier fail.

ERROR in Error: Parse Error: <html lang="en">\r\n\r\n\r\n <meta chars
et="UTF- 8">\r\n\r\n <title>slider</title>\r\n <meta name="viewport"\r\n
co ntent="width=device-width, initial-scale=1.0, user-scalable=no, mini
mum-scale =1.0, maximum-scale=1.0">\r\n\r\n\r\n\r\n

    \r\n\r\n</
    ul>\r\n\r \n<script type="text/javascript" src=".././js/vendors.js?271daa494a16 c3d5e559" ></script><script type="text/javascript" src=".././js/slider.js?271da a494a16c3 d5e559"></script>\r\n\r\n"

    • htmlparser.js:235 new HTMLParser
      [Component]/[html-minifier]/src/htmlparser.js:235:13

    • htmlminifier.js:944 minify
      [Component]/[html-minifier]/src/htmlminifier.js:944:3

    • htmlminifier.js:1304 exports.minify
      [Component]/[html-minifier]/src/htmlminifier.js:1304:10

    • index.js:309 Promise.resolve.then.then.html
      [Component]/[html-webpack-plugin]/index.js:309:18

    • next_tick.js:188 process._tickCallback
      internal/process/next_tick.js:188:7

    here is my config:
    "css-loader": "^0.28.10",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.0.6",
    "raw-loader": "^0.5.1",
    "style-loader": "^0.20.2",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.10",
    "webpack-dev-server": "^3.1.0"

    after i remove the raw-loader, it is fine !

Syntax error with special whitespace characters

I was trying to load a text file that was written with Google Docs. It had issues like the character for " was the special “.

But that was not my issue.
It turns out that a special whitespace character was put in the file. I used String.charCodeAt to find out the whitespace was of code: 8232 or

U+2028 | line separator

I replaced all these characters and the raw-loader now works.
I'm filing this issue because I think that there needs to be some pre-processing to replace or correctly JSON stringify these characters.

The template specified for component AppComponent is not a string

When i try to upgrade an existing angular app using webpack , raw-loader, to 2.0.0 started receiving this error.
webpack build was successful, but when i ran the app in browser got this error.

when i downgraded to earlier version of raw-loader its working fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.